package part1.task1;


public class Main {
    public static final Function sin =new Function() {
        @Override
        public double call(double x) {
            return Math.sin(x);
        }
    };

    public static void main(String[] args) throws InterruptedException{
        int n=8;
        int N=2000000;
        int startX=-N;
        double taskStep=(2*N+1)/n;
        ThreadTask tasks[]=new ThreadTask[n];
        for (int i = 0; i < n; i++,startX+=taskStep) {
            tasks[i]=new ThreadTask(sin,startX,i==n-1?N+1:startX+taskStep,1);
            tasks[i].start();
        }
        Thread.yield();
        double sum=0;
        for (ThreadTask task:tasks){
            task.join();
            sum+=task.getResult();
        }

        System.out.println("Sum of sin(x) where x from "+-N+" to "+N+" on is: "+sum+" "+n);
    }
}

interface Function {
    double call(double x);
}

class ThreadTask extends Thread{
    private Function function;
    private double startX, endX, stepX;
    private volatile double result;

    public ThreadTask(Function function, double startX, double endX, double stepX){
        setDaemon(true);
        this.function=function;
        this.startX=startX;
        this.endX=endX;
        this.stepX=stepX;
    }

    @Override
    public void run() {
        double sum=0;
        for (double x = startX; x <endX; x+=stepX) {
            sum+=function.call(x);
        }
        result=sum;
    }

    public double getResult() {
        return result;
    }
}